package com.crm.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlDateUtil {
	public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
	public static final String DEFAULT_TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String[] DATE_PATTERN = { "y", "M", "d", "H", "m", "s",
			"S" };

	public static String currentDateString() {
		return currentDateString("yyyy-MM-dd");
	}

	public static String currentDateString(String pattern) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		String result = simpleFormat.format(new java.sql.Date(System
				.currentTimeMillis()));
		return result;
	}

	public static java.sql.Date currentDate() {
		return new java.sql.Date(System.currentTimeMillis());
	}

	public static java.sql.Date parseDate(int year, int month, int day)
			throws Exception {
		validateDate(year, month, day);
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month - 1, day);
		java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis());
		return date;
	}

	public static java.sql.Date parseDate(String dateStr) throws Exception {
		String[] dateArr = dateStr.split("-");
		int year = Integer.parseInt(dateArr[0]);
		int month = Integer.parseInt(dateArr[1]);
		int day = Integer.parseInt(dateArr[2]);
		java.sql.Date date = parseDate(year, month, day);
		return date;
	}

	public static java.sql.Date parseDate(String dateStr, String pattern)
			throws ParseException {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		java.sql.Date date = new java.sql.Date(simpleFormat.parse(dateStr)
				.getTime());
		return date;
	}

	public static String currentTimestampString() {
		return currentTimestampString("yyyy-MM-dd HH:mm:ss");
	}

	public static String currentTimestampString(String pattern) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		String result = simpleFormat.format(new Timestamp(System
				.currentTimeMillis()));
		return result;
	}

	public static String formatTimestamp(Timestamp timestamp, String pattern) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		String result = simpleFormat.format(timestamp);
		return result;
	}

	public static String formatTimestamp(Timestamp timestamp) {
		return formatTimestamp(timestamp, "yyyy-MM-dd");
	}

	public static String formatDate(java.sql.Date date, String pattern) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		String result = simpleFormat.format(date);
		return result;
	}

	public static String formatDate(java.sql.Date date) {
		return formatDate(date, "yyyy-MM-dd");
	}

	public static Timestamp currentTimestamp() {
		return new Timestamp(System.currentTimeMillis());
	}

	public static Timestamp parseTimestamp(int year, int month, int day,
			int hour, int minute, int second) throws Exception {
		validateTimestamp(year, month, day, hour, minute, second);
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month - 1, day, hour, minute, second);
		Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
		return timestamp;
	}

	public static Timestamp parseTimestamp(String timestampStr, String pattern)
			throws Exception {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(pattern);
		Timestamp Timestamp = null;
		try {
			Timestamp = new Timestamp(simpleFormat.parse(timestampStr)
					.getTime());
		} catch (ParseException ex) {
			throw new Exception("", ex);
		}
		return Timestamp;
	}

	public static Timestamp parseTimestamp(String timestampStr)
			throws Exception {
		return parseTimestamp(timestampStr, "yyyy-MM-dd");
	}

	public static String firstDayForYear() {
		Calendar calendar = Calendar.getInstance();
		return String.valueOf(calendar.get(1)) + "-01-01";
	}

	private static void validateTimestamp(int year, int month, int day,
			int hour, int minute, int second) throws Exception {
		if ((year < 1900) || (year > 2400)) {
			throw new Exception("Date parse error: the year is invalid.");
		}
		if ((month < 1) || (month > 12)) {
			throw new Exception("Date parse error: the month is invalid.");
		}
		if ((day < 1) || (day > 31)) {
			throw new Exception("Date parse error: the day is invalid.");
		}
		if ((hour < 0) || (hour > 23)) {
			throw new Exception("Date parse error: the day is invalid.");
		}
		if ((minute < 0) || (minute > 59)) {
			throw new Exception("Date parse error: the day is invalid.");
		}
		if ((second < 0) || (second > 59))
			throw new Exception("Date parse error: the day is invalid.");
	}

	private static void validateDate(int year, int month, int day)
			throws Exception {
		if ((year < 1900) || (year > 2400))
			throw new Exception("Date parse error: the year is invalid.");
		if ((month < 1) || (month > 12))
			throw new Exception("Date parse error: the month is invalid.");
		if ((day < 1) || (day > 31))
			throw new Exception("Date parse error: the day is invalid.");
	}

	public static String getYear() {
		Calendar c = Calendar.getInstance();
		return Integer.toString(c.get(1));
	}

	public static String getMonth() {
		Calendar c = Calendar.getInstance();
		int i = c.get(2) + 1;
		String s = null;
		if (i < 10)
			s = "0" + String.valueOf(i);
		else {
			s = String.valueOf(i);
		}
		return s;
	}

	public static String getDay() {
		Calendar c = Calendar.getInstance();
		return Integer.toString(c.get(5));
	}

	public static String getDate() {
		Calendar c = Calendar.getInstance();
		DateFormat df = DateFormat.getDateInstance();
		return df.format(c.getTime());
	}

	public static String getDateTime() {
		Calendar c = Calendar.getInstance();
		DateFormat df = DateFormat.getDateTimeInstance();
		return df.format(c.getTime());
	}

	public static String getTime() {
		Calendar c = Calendar.getInstance();
		DateFormat df = DateFormat.getTimeInstance();
		return df.format(c.getTime());
	}

	public static java.sql.Date getSqlDate() {
		return new java.sql.Date(System.currentTimeMillis());
	}

	public static java.util.Date getUtilDate() {
		return new java.util.Date(System.currentTimeMillis());
	}

	public static void addDay(java.util.Date date, int day) {
		date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000L);
	}

	public static void addHour(java.util.Date date, int hour) {
		date.setTime(date.getTime() + hour * 60 * 60 * 1000L);
	}

	public static void addMinute(java.util.Date date, int minute) {
		date.setTime(date.getTime() + minute * 60 * 1000L);
	}

	public static void addSecond(java.util.Date date, int second) {
		date.setTime(date.getTime() + second * 1000L);
	}

	public static void addMonth(java.util.Date date, int month) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(2, month);
		date.setTime(c.getTime().getTime());
	}

	public static void addYear(java.util.Date date, int year) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(1, year);
		date.setTime(c.getTime().getTime());
	}

	public static java.sql.Date addVeryDate(java.util.Date d_end, int timeNum,
			char pattern) {
		java.sql.Date d = new java.sql.Date(d_end.getTime());
		switch (pattern) {
		case 'y':
			addYear(d, timeNum);
			break;
		case 'M':
			addMonth(d, timeNum);
			break;
		case 'd':
			addDay(d, timeNum);
			break;
		case 'H':
			addHour(d, timeNum);
			break;
		case 'm':
			addMinute(d, timeNum);
			break;
		case 's':
			addSecond(d, timeNum);
		}

		return d;
	}

	public static java.util.Date parseToUtilDate(String dateStr) {
		return parseToUtilDate(dateStr, getDatePattern(dateStr));
	}

	public static java.util.Date parseToUtilDate(String dateStr,
			String datePattern) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(datePattern);
		try {
			return simpleFormat.parse(dateStr);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}

	}

	public static java.sql.Date parseToSQLDate(String dateStr) {
		return new java.sql.Date(parseToUtilDate(dateStr).getTime());
	}

	public static java.sql.Date parseToSQLDate(String dateStr,
			String datePattern) {
		return new java.sql.Date(parseToUtilDate(dateStr, datePattern)
				.getTime());
	}

	public static Timestamp parseToTimestamp(String dateStr) {
		return new Timestamp(parseToSQLDate(dateStr).getTime());
	}

	public static String formatDate(Object date) {
		return formatDate(date, "yyyy-MM-dd");
	}

	public static String formatDate(Object date, String format) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
		return simpleFormat.format(date);
	}

	public static String formatDateTime(Object date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String formatDateTime(Object date, String format) {
		return formatDate(date, format);
	}

	public static Timestamp getSqlTimestamp() {
		return new Timestamp(getSqlDate().getTime());
	}

	private static String getDatePattern(String dateString) {
		String temp = dateString;
		Pattern regexPattern = Pattern.compile("(\\d+)([\\D]{1})(.+)");
		Matcher m = regexPattern.matcher(temp);
		StringBuffer sb = new StringBuffer();
		int j = 0;
		while (m.matches()) {
			sb.append(m.group(1).replaceAll("\\d{1}", DATE_PATTERN[(j++)]));
			sb.append(m.group(2));
			temp = m.group(3);
			m = regexPattern.matcher(temp);
		}
		sb.append(temp.replaceAll("\\d{1}", DATE_PATTERN[(j++)]));
		return sb.toString();
	}

	public static java.sql.Date format2Date(String date, String format) {
		SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
		try {
			return (java.sql.Date) simpleFormat
					.parse(simpleFormat.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getLastDayOfMonth(java.util.Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(5, 1);
		cal.roll(5, -1);
		cal.setTime(cal.getTime());
		return Integer.toString(cal.get(5));
	}

	public static String getDate(String year, String month, String tenDays) {
		StringBuilder firstDayOfMonth = new StringBuilder();

		StringBuilder builder = new StringBuilder();
		firstDayOfMonth.append(year).append("-");
		builder.append(year).append("-");
		if ((Integer.valueOf(month).intValue() < 10) && (month.length() < 2)) {
			firstDayOfMonth.append("0" + month).append("-");
			builder.append("0" + month).append("-");
		} else {
			firstDayOfMonth.append(month).append("-");
			builder.append(month).append("-");
		}
		if ("3".equals(tenDays))
			builder.append(getLastDayOfMonth(parseToUtilDate(firstDayOfMonth
					.toString())));
		else if ("2".equals(tenDays))
			builder.append("20");
		else {
			builder.append("10");
		}
		return builder.toString();
	}

	public static boolean isDate(String dateStr, String dateFormat) {
		if (dateStr != null && dateStr.trim().length() > 0) {
			SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
			formatter.setLenient(false);
			try {
				formatter.format(formatter.parse(dateStr));
			} catch (Exception e) {
				return false;
			}
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
	}
}